package com.rabbitmq.rabbit;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * @Author: TongRui乀
 * @Date: 2019/8/5 10:43
 * @description：
 */
@Component
@Slf4j
public class LogMessageMultiConusmerListener {


    @RabbitListener(queues = "${log.queue.multi.consumer.name}", containerFactory = "multiListenerContainer")
    public void receiveMessage(Message message, Channel channel){

        String msg = new String(message.getBody());

        log.info("Log Listener receive message :[{}] channel :[{}]", msg, channel.getChannelNumber());

        long tag = message.getMessageProperties().getDeliveryTag();

        try {
            Random random = new Random();

            /*int num = random.nextInt(10);
            if(num % 2 ==0){
                log.info("消费");
                channel.basicAck(tag,true);
            }else{
                log.info("重试");
                channel.basicNack(tag, true, true);
            }*/
            channel.basicReject(tag, false);
        } catch (IOException e) {
            e.printStackTrace();
        }

        /*try {
            channel.basicAck(tag, true);
        } catch (IOException e) {
            e.printStackTrace();
        }*/
    }

    /**
     * 消息进入死信队列的三种情况
     * 1 The message is negatively acknowledged by a consumer using basic.reject or basic.nack with requeue parameter set to false.
     *     消费者调用 basic.reject basic.nack 并设置 requeue parameter 为false
     * 2 The message expires due to per-message TTL; or
     *      由于设置的消息的TTL超时
     * 3 The message is dropped because its queue exceeded a length limit
     *      由于队列已满导致被删除
     *
     * @param message
     * @param channel
     */
    @RabbitListener(queues = "${dead.queue.name}")
    public void receiveMessage2(Message message, Channel channel){

        String msg = new String(message.getBody());

        log.info("Log dead Listener receive message :[{}] channel :[{}]", msg, channel.getChannelNumber());

        long tag = message.getMessageProperties().getDeliveryTag();

        log.info(message.toString());

        try {
            channel.basicAck(tag,true);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }


}
